"""
Support module for portscanner.py to gather local computer IP addresses.

This module checks system for each interface IP address and netmask
"""

import commands

class NetworkInterface:
	"""Stores network interface proprieties
	
	Keyword arguments:
    interfaceName -- Interface Name
	ipAddress -- Interface IP Address
    netmask -- Interface Netmask
	
	"""
	def __init__(self,interfaceName,ipAddress,netmask):
		"""Default Constructor"""
		self.interfaceName = interfaceName
		self.ipAddress = ipAddress
		self.netmask = netmask
		
	def __str__(self):
		"""String Output"""
		return "Interface " + self.interfaceName + "\tIp: " + self.ipAddress + " Netmask: " + self.netmask

def getLocalIps():
	"""Gets System Interfaces and their proprieties"""
	interfaceList = []
	interfaces = commands.getoutput("/sbin/ifconfig").split("\n\n");
	for x in interfaces:
		try:
			a = x.split(' ')[0]
			b = validateIP(x.split("\n")[1].split()[1][5:])
			c = validateIP(x.split("\n")[1].split()[3][5:])
		except:
			c = ''
		if all((a,b,c)):
			inter = NetworkInterface(a,b,c)
			interfaceList.append(inter)
	return interfaceList
	
def validateIP(ip):
	"""Simple IP Validator
	
	Keyword arguments:
    ip -- IP Address to Validate
	
	"""
	try:
		parts = ip.split('.')
		if(len(parts) == 4 and all(0 <= int(part) < 256 for part in parts)):
			return ip		
	except ValueError:
		return ''
	except (AttributeError, TypeError):
		return ''
	return ''


